package main

import (
	"fmt"
	"github.com/hashicorp/mdns"
	"log"
	"net"
	"os"
)

func main() {
	var info []string
	if adps, err := net.Interfaces(); err != nil {
		log.Printf("leenux- Error get net card error:%v\n", err)
		return
	} else {
		for _, a := range adps {
			log.Printf("leenux- net card:%v,va %v\n", a.Flags, a.Flags&net.FlagLoopback)
			if (a.Flags & net.FlagLoopback) == 0 {
				if b, err := a.Addrs(); err != nil {
					continue
				} else {
					for _, i := range b {
						if !i.(*net.IPNet).IP.IsLoopback() && i.(*net.IPNet).IP.To4() != nil {
							info = append(info, fmt.Sprintf("tcp://%v:1883", i.(*net.IPNet).IP.String()))
							log.Printf("leenux- IP:%s\n", i.(*net.IPNet).IP.String())

						}
					}
				}
			}
		}
	}
	//if adp[0].Flags == net.FlagLoopback {
	//	adp[0].Addrs()
	//}
	//addrs, err := net.InterfaceAddrs()
	//if err != nil {
	//	fmt.Println(err)
	//	return
	//}
	////var ips []net.IP
	//var info []string
	//for _, address := range addrs {
	//	if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() &&
	//		!ipnet.IP.IsInterfaceLocalMulticast() && !ipnet.IP.IsMulticast() {
	//		if ipnet.IP.To4() != nil {
	//			info = append(info, fmt.Sprintf("tcp://%v:1883", ipnet.IP.String()))
	//			log.Printf("leenux- IP:%s\n", ipnet.IP.String())
	//			//ips = append(ips, ipnet.IP)
	//			//fmt.Println(ipnet.IP.String())
	//		}
	//	}
	//}
	if len(info) == 0 {
		log.Printf("leenux- No valid IP addresses found\n")
		return
	}
	//var info []string
	//for _, ip := range ips {
	//	info = append(info, fmt.Sprintf("tcp://%v:1883", ip.String()))
	//	log.Printf("leenux- IP:%s\n", ip.String())
	//}
	host, _ := os.Hostname()
	//info := []string{"My awesome service"}
	service, _ := mdns.NewMDNSService(host, "_leenux._tcp", "", "", 8000, nil, info)

	// Create the mDNS server, defer shutdown
	server, _ := mdns.NewServer(&mdns.Config{Zone: service})
	defer server.Shutdown()

	b := make([]byte, 1)
	os.Stdin.Read(b)
}
